package jdbc;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class TestJDBC {
    public static void main(String[] args) throws SQLException {
        // 0. 用户输入实现构造sql语句
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入插入的id：");
        int id = scanner.nextInt();
        System.out.println("请输入插入的用户name：");
        String name = scanner.next();

        // 1. 创建数据源对象
        MysqlDataSource dataSource = new MysqlDataSource();
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false");
        dataSource.setUser("root");
        dataSource.setPassword("1234");

        // 2. 和数据库建立网络连接
        Connection connection = dataSource.getConnection();
        System.out.println(connection);

        // 3. 构造sql语句
        //    PreparedStatement库
        String sql = "insert into student values(" + id +",'" + name + "')";
//        String sql = "insert into student values (?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
//        statement.setInt(1,id);
//        statement.setString(2,name);


        // 4. 把sql语句发送到数据库
//        int n = statement.executeUpdate(); //返回为几行收到了改动 因此是整数
//        System.out.println(n);
        statement.execute(); //返回为bool类型 表示是否更新成功！
        // 5. 释放上述资源
        statement.close();
        connection.close();
    }
}
